package util

import (
	"errors"
	"github.com/hashicorp/consul/api"
)

type Consul struct {
	Client  *api.Client
	Address string
}

func NewConsul(address string) (*Consul, error) {
	ConsulConfig := api.DefaultConfig()
	ConsulConfig.Address = address
	client, err := api.NewClient(ConsulConfig)
	if err != nil {
		return &Consul{}, err
	}
	if _, err := client.Status().Leader(); err != nil {
		return &Consul{}, err
	}
	return &Consul{
		Address: address,
		Client:  client,
	}, nil
}

func (m *Consul) Set(key string, val []byte) error {
	if key == "" {
		return errors.New("consul setting key is empty")
	}
	if len(val) == 0 {
		return errors.New("consul setting val is empty")
	}

	kv := m.Client.KV()
	p := &api.KVPair{Key: key, Value: val}
	_, err := kv.Put(p, nil)
	return err
}

func (m *Consul) Get(key string) (string, error) {
	if key == "" {
		return "", errors.New("consul setting key is empty")
	}
	kv := m.Client.KV()
	pair, _, err := kv.Get(key, nil)
	if err != nil {
		return "", err
	}
	return string(pair.Value), nil
}
